﻿(function (aspnetinfo, $, undefined) {
    var emailFrom,
        emailTo,
        emailFormat,
        emailSubject,
        emailMessage,
        smtpCustom,
        smtpHost,
        smtpPort,
        smtpDeliveryMethod,
        smtpPickupDir,
        smtpUseDefaultCredentials,
        smtpUsername,
        smtpPassword,
        allFields,
        tabEmail,
        tabSmtp;


    function updateTips(t) {
        $("#emailValidateTips").text(t).effect("highlight", {}, 1500);
    }

    function checkLength(o, n, min, max) {

        if (o.val().length > max || o.val().length < min) {
            o.addClass('ui-state-error');
            updateTips("Length of " + n + " must be between " + min + " and " + max + ".");
            return false;
        } else {
            return true;
        }

    }

    function checkRange(o, n, min, max) {
        if (o.val() > max || o.val() < min) {
            o.addClass('ui-state-error');
            updateTips(n + " must be a number between " + min + " and " + max + ".");
            return false;
        } else {
            return true;
        }
    }

    function checkRegexp(o, regexp, n) {

        if (!(regexp.test(o.val()))) {
            o.addClass('ui-state-error');
            updateTips(n);
            return false;
        } else {
            return true;
        }

    }
    function toggleCredentials() {
        if (smtpUseDefaultCredentials.is(":checked") == false && smtpCustom.is(":checked")) {
            $(".credential").removeAttr("disabled");
        } else {
            $(".credential").attr("disabled", true);
        }
    }

    function toggleDeliveryMethod() {
        if (smtpDeliveryMethod.val() == "SpecifiedPickupDirectory" && smtpCustom.is(":checked")) {
            $(".delivery").removeAttr("disabled");
        } else {
            $(".delivery").attr("disabled", true);
        }
    }

    function toggleSmtpCustom() {
        if (smtpCustom.is(":checked")) {
            $("#customsmtp :input").removeAttr("disabled");
        } else {
            $("#customsmtp :input").attr("disabled", true);
        }

        smtpCustom.removeAttr("disabled");

        toggleCredentials();
        toggleDeliveryMethod();
    }


    function SendTestEmail() {
        aspnetinfo.callPageMethod("TestEmail",
                    function (response) {
                        aspnetinfo.showMessageDialog(response.d);
                    },
                    function (response) {
                        aspnetinfo.showMessageDialog(response.d);
                    },
                    "from", emailFrom.val(),
                    "to", emailTo.val(),
                    "format", emailFormat.val(),
                    "subject", emailSubject.val(),
                    "message", emailMessage.val(),
                    "customSmtp", smtpCustom.is(":checked"),
                    "host", smtpHost.val(),
                    "port", smtpPort.val(),
                    "deliveryMethod", smtpDeliveryMethod.val(),
                    "pickupDir", smtpPickupDir.val(),
                    "defaultCreds", smtpUseDefaultCredentials.is(":checked"),
                    "username", smtpUsername.val(),
                    "password", smtpPassword.val());
    }




    // public method
    aspnetinfo.init = function (options) {
        settings = $.extend({
            debug: true
        }, options);

        emailFrom = $("#emailFrom");
        emailTo = $("#emailTo");
        emailFormat = $("input[@name='emailFormat']:checked");
        emailSubject = $("#emailSubject");
        emailMessage = $("#emailMessage");
        smtpCustom = $("#smtpUseCustomSmtp");
        smtpHost = $("#smtpHost");
        smtpPort = $("#smtpPort");
        smtpDeliveryMethod = $("#SmtpDeliveryMethod");
        smtpPickupDir = $("#smtpPickupDir");
        smtpUseDefaultCredentials = $("#smtpUseDefaultCreds");
        smtpUsername = $("#smtpUsername");
        smtpPassword = $("#smtpPass");
        allFields = $([]).add(emailFrom).add(emailTo).add(emailFormat).add(emailSubject).add(emailMessage).add(smtpCustom).add(smtpHost).add(smtpPort).add(smtpDeliveryMethod).add(smtpPickupDir).add(smtpUseDefaultCredentials).add(smtpUsername).add(smtpPassword);
        tabEmail = 0;
        tabSmtp = 1;


        $('#tabs').tabs();

        $('.test-run-button')
            .hover(
                function () {
                    $(this).children('img').attr('src', aspnetinfo.diagStatus.starthover);
                },
                function () {
                    $(this).children('img').attr('src', aspnetinfo.diagStatus.start);
                })
            .click(
                function (e) {
                    $(this).hide().after('<img class="diag-result" src="' + aspnetinfo.diagStatus.running + '" alt="running" />');
                    aspnetinfo.callPageMethod("ExecuteDiagnostic", onExecuteDiagnosticCompleted, onExecuteDiagnosticFailed, "testName", $(this).attr('data-name'));
                });



        $("#emailTabs").tabs();

        $("#emailDialog").dialog({
            bgiframe: true,
            autoOpen: false,
            height: 500,
            width: 700,
            modal: true,
            buttons: {
                'Send test email': function () {
                    var bValid = true;
                    var errorTab = tabEmail;
                    allFields.removeClass('ui-state-error');
                    bValid = true;
                    bValid = bValid && checkRegexp(emailFrom, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "Please provide a proper email address. eg. info@mydomain.com");
                    bValid = bValid && checkRegexp(emailTo, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "Please provide a proper email address. eg. info@mydomain.com");
                    bValid = bValid && checkLength(emailSubject, "subject", 1, 80);
                    bValid = bValid && checkLength(emailMessage, "message", 1, 1024);
                    if (smtpCustom.is(":checked")) {
                        errorTab = bValid ? tabSmtp : tabEmail;
                        bValid = bValid && checkLength(smtpHost, "host", 1, 255);
                        bValid = bValid && checkRegexp(smtpPort, /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/, "Port must be a number.");
                        bValid = bValid && checkRange(smtpPort, "port", 1, 65535);
                        if (smtpDeliveryMethod.val() == "SpecifiedPickupDirectory") {
                            bValid = bValid && checkLength(smtpPickupDir, "pickup directory", 1, 1024);
                        }
                        if (smtpUseDefaultCredentials.is(":checked") == false) {
                            bValid = bValid && checkLength(smtpUsername, "username", 1, 255);
                            bValid = bValid && checkLength(smtpPassword, "password", 1, 255);
                        }
                    }

                    if (bValid) {
                        SendTestEmail();
                    } else {
                        $("#emailTabs").tabs('select', errorTab);
                    }
                },
                Cancel: function () {
                    $(this).dialog('close');
                }
            },
            close: function () {
                allFields.val('').removeClass('ui-state-error');
            }
        });

        $('#send-email').button().click(function () {
            $('#emailDialog').dialog('open');
            return false;
        });

        smtpCustom.click(function () {
            toggleSmtpCustom();
        });

        smtpUseDefaultCredentials.click(function () {
            toggleCredentials();
        });

        smtpDeliveryMethod.click(function () {
            toggleDeliveryMethod();
        });

        toggleSmtpCustom();

        $('#diag-run-button').button().click(function () {
            aspnetinfo.runAllDiagnostics = true;
            $('.test-run-button').attr('data-status', 'new').show();
            $('.diag-result').remove();
            $('.diag-message').remove();

            runNextDiagnostic();
            $('#diag-button-panel a').hide();
            $('#diag-run-message').show();
        });
    }

    aspnetinfo.showMessageDialog = function (message) {
        $('#dialog-message').html('<span class="ui-icon ui-icon-circle-check" style="float:left; margin:0 7px 50px 0;"></span>' + message);
        $("#dialog-message").dialog({
            modal: true,
            buttons: {
                Ok: function () {
                    $(this).dialog("close");
                }
            }
        });
    }

    aspnetinfo.callPageMethod = function (methodName, onSuccess, onFail) {
        var args = '';
        var l = arguments.length;
        if (l > 3) {
            for (var i = 3; i < l - 1; i += 2) {
                if (args.length != 0) args += ',';
                args += '"' + arguments[i] + '":"' + arguments[i + 1] + '"';
            }
        }
        var loc = window.location.href;
        loc = (loc.substr(loc.length - 1, 1) == "/") ? loc + "default.aspx" : loc;
        $.ajax({
            type: "POST",
            url: loc + "/" + methodName,
            data: "{" + args + "}",
            contentType: "application/json; charset=utf-8;",
            dataType: "json",
            success: onSuccess,
            fail: onFail
        });
    }

    aspnetinfo.runAllDiagnostics = false;
    // private method

    function onExecuteDiagnosticCompleted(response) {
        var testName = response.d.Name;

        var testStatus = $('.test-run-button[data-name="' + testName + '"]');
        if (response.d.Status == 1) {
            testStatus.next('img').attr('src', aspnetinfo.diagStatus.passed);
        } else {
            testStatus.next('img').attr('src', aspnetinfo.diagStatus.failed);
            $('#alertTemplate').tmpl(response.d.Messages).appendTo('.test[data-name="' + testName + '"]');
        }
        testStatus.attr('data-status', 'complete');

        runNextDiagnostic();
    }
    function onExecuteDiagnosticFailed(response) {
        alert("An error occurred.");
        runNextDiagnostic();
    }

    function runNextDiagnostic() {
        if (!aspnetinfo.runAllDiagnostics) { return; }

        var nextDiagnostic = $('.test-run-button[data-status!="complete"]');
        if (nextDiagnostic.length > 0) {
            nextDiagnostic.first().click();
        } else {
            aspnetinfo.runAllDiagnostics = false;
            $('#diag-button-panel a').show();
            $('#diag-run-message').hide();
        }

    }


} (window.aspnetinfo = window.aspnetinfo || {}, jQuery));